package com.wohuijituan.whcsmerchant.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.wohuijituan.whcsmerchant.R;
import com.wohuijituan.whcsmerchant.adapter.SelectBankCardAdapter;
import com.wohuijituan.whcsmerchant.bean.BankListBean;
import com.wohuijituan.whcsmerchant.bean.DrawMoneyAmountBean;
import com.wohuijituan.whcsmerchant.bean.IsSuccessBean;
import com.wohuijituan.whcsmerchant.callback.BankListCallBack;
import com.wohuijituan.whcsmerchant.callback.DrawMoneyAmountCallBack;
import com.wohuijituan.whcsmerchant.callback.IsSuccessCallBack;
import com.wohuijituan.whcsmerchant.url.ParamsKey;
import com.wohuijituan.whcsmerchant.url.Urls;
import com.wohuijituan.whcsmerchant.utils.CashierInputFilter;
import com.wohuijituan.whcsmerchant.utils.LogUtils;
import com.wohuijituan.whcsmerchant.utils.MyOkHttpUtils;
import com.wohuijituan.whcsmerchant.utils.MyRequestParams;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

public class DrawMoneyActivity extends MyBaseActivity implements View.OnClickListener {
    private static final String TAG = "DrawMoneyActivity";
    private LinearLayout llAddBank;
    private ImageView ivBankIcon;
    private TextView tvBankName;
    private TextView tvBankCardNumber;
    private TextView tvMoneyRemain;
    private Button btnConfirmDraw;
    private ImageButton titleGoBack;
    private TextView titleName;
    private TextView tvDrawMoneyAll;
    private TextView titleAction;
    private EditText etInputPrice;
    private LinearLayout llSelectBank;
    private List<BankListBean.DataEntity> bankList;
    private SelectBankCardAdapter bankCardAdapter;
    private MyOkHttpUtils myOkHttpUtils;
    private MyRequestParams params;
    private static final int BANK_LIST_REQUEST_OK = 2229;
    private static final int BANK_LIST_REQUEST_FAIL = 2228;

    private void assignViews() {
        llSelectBank = (LinearLayout) findViewById(R.id.ll_select_bank);
        llAddBank = (LinearLayout) findViewById(R.id.ll_add_bank);
        ivBankIcon = (ImageView) findViewById(R.id.iv_bank_icon);
        tvBankName = (TextView) findViewById(R.id.tv_bank_name);
        tvBankCardNumber = (TextView) findViewById(R.id.tv_bank_card_number);
        tvMoneyRemain = (TextView) findViewById(R.id.tv_money_remain);
        btnConfirmDraw = (Button) findViewById(R.id.btn_confirm_draw);
        titleGoBack = (ImageButton) findViewById(R.id.title_go_back);
        titleName = (TextView) findViewById(R.id.title_name);
        titleAction = (TextView) findViewById(R.id.title_tv_action);
        etInputPrice = (EditText) findViewById(R.id.et_input_price);
        tvDrawMoneyAll = (TextView) findViewById(R.id.tv_draw_money_all);
    }
    //用于图片加载
    private DisplayImageOptions mImageOptions;
    private ImageLoader mImageLoader;
    private BankListBean.DataEntity selectBank;//选择的银行卡
    private double drawableMoney = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_draw_money);
        assignViews();
        initData();
        initView();
        initListener();
        bankListRequest();
        drawMoneyAmountRequest();
    }

    private void initView() {
        titleGoBack.setVisibility(View.VISIBLE);
        titleName.setText(R.string.draw_money);
        titleAction.setVisibility(View.GONE);
        //初始化金额编辑框
        //直接调出输入数字软键盘
        etInputPrice.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        //添加只能输入金额的过滤器
        InputFilter[] filters = {new CashierInputFilter()};
        etInputPrice.setFilters(filters);
    }
    private void initListener() {
        llSelectBank.setOnClickListener(this);
        btnConfirmDraw.setOnClickListener(this);
        titleGoBack.setOnClickListener(this);
        llAddBank.setOnClickListener(this);
        tvDrawMoneyAll.setOnClickListener(this);
        etInputPrice.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                LogUtils.e("beforeTextChanged"+"s:"+s+"start"+start+"count:"+count+"after:"+after);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // TODO: 2016/10/8 如果输入大于可提现金额,则变成可提现金额
                LogUtils.e("onTextChanged"+"s:"+s+"start"+start+"before:"+before+"count:"+count);
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (null!=s&&!"".equals(s.toString())){
                    double price = Double.parseDouble(s.toString());
                    if (price>drawableMoney){
                        etInputPrice.setText(drawableMoney+"");
                    }
                    LogUtils.e("afterTextChanged"+"s:"+s);
                    if (s.toString().trim().length() > 0) {
                        btnConfirmDraw.setEnabled(true);
                    }
                }

            }
        });
    }
    /**
     * 初始化银行卡
     * @param selectBank
     */
    private void initSelectBank(BankListBean.DataEntity selectBank){
        llSelectBank.setVisibility(View.VISIBLE);
        llAddBank.setVisibility(View.GONE);
        mImageLoader.displayImage(selectBank.getB_Icon(),ivBankIcon,mImageOptions);
        tvBankName.setText(selectBank.getB_Name());
        String cardNumber = selectBank.getSMB_Number();
        String end = cardNumber.substring(cardNumber.length()-4);//截取字符串后四位
        tvBankCardNumber.setText("尾号"+end);
    }
    private void drawMoneyAmountRequest(){
        params.clear();
        String strUrl = Urls.DrawMoneyAmount;
        params.addStringRequest(ParamsKey.UserKey,myApplication.getUserKey());
        myOkHttpUtils.postRequest(strUrl, params, new DrawMoneyAmountCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast(ctx, "获取可提现金额失败,请检查网络是否连接!");
            }

            @Override
            public void onResponse(DrawMoneyAmountBean response, int id) {
                Message msg = new Message();
                msg.what = DRAWABLE_MONEY_REQUEST_OK;
                msg.obj = response;
                handler.sendMessage(msg);
            }
        });
    }
    /**
     * 网络请求,获取银行卡列表
     */
    private void bankListRequest() {
        showDialog(ctx);
        String strUrl = Urls.BankList;
        params.clear();
        params.addStringRequest(ParamsKey.UserKey, myApplication.getUserKey());
        myOkHttpUtils.postRequest(strUrl, params, new BankListCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                showToast(ctx, "获取银行卡列表失败,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
                handler.sendEmptyMessage(BANK_LIST_REQUEST_FAIL);
            }
            @Override
            public void onResponse(BankListBean response, int id) {

                if (response.getState() == 1) {//如果银行卡列表不为零个则成功,否则失败
                    if (response.getData().size() > 0) {
                        Message msg = new Message();
                        msg.what = BANK_LIST_REQUEST_OK;
                        msg.obj = response;
                        handler.sendMessage(msg);
                    } else {
                        handler.sendEmptyMessage(BANK_LIST_REQUEST_FAIL);
                    }

                } else {
                    showToast(ctx, response.getMsg());
                    handler.sendEmptyMessage(BANK_LIST_REQUEST_FAIL);
                }
            }
        });
    }

    /**
     * 提现
     *
     * @param bankID    银行卡在数据库中的序号
     * @param drawMoney 提现金额
     */
    private void withdrawMoney(String bankID, double drawMoney) {
        showDialog(ctx);
        String strUrl = Urls.WithdrawMoney;
        params.clear();
        params.addStringRequest(ParamsKey.UserKey, myApplication.getUserKey());
        params.addStringRequest(ParamsKey.WithdrawMoney_BankID, bankID);
        params.addStringRequest(ParamsKey.WithdrawMoney_Money, drawMoney + "");
        myOkHttpUtils.postRequest(strUrl, params, new IsSuccessCallBack() {
            @Override
            public void onError(Call call, Exception e, int id) {
                dismissDialog();
                showToast(ctx, "网络出错,请检查网络是否连接!");
                LogUtils.e(TAG, e.getMessage());
            }

            @Override
            public void onResponse(IsSuccessBean response, int id) {
                if (response.getState() == 1) {
                    if (response.getData().isIsSuccess()) {
                        // TODO: 2016/10/8 提现成功,对剩余金额的处理
                        handler.sendEmptyMessage(DRAW_MONEY_REQUEST_OK);
                        showToast(ctx,response.getData().getMessage());
                    } else {
                        showToast(ctx, "失败:" + response.getData().getMessage());
                        dismissDialog();
                    }
                } else {
                    showToast(ctx, "失败:" + response.getData().getMessage());
                    dismissDialog();
                }
            }
        });
    }



    private void initData() {
        bankList = new ArrayList<>();
        bankCardAdapter = new SelectBankCardAdapter(this, bankList);
        mImageLoader= ImageLoader.getInstance();
        mImageOptions = new DisplayImageOptions.Builder()
                .cacheInMemory(true)
                .cacheOnDisk(true)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .showImageForEmptyUri(R.drawable.icon_nonghang)
                .showImageOnLoading(R.drawable.icon_nonghang)
                .showImageOnFail(R.drawable.icon_nonghang)
                .build();
        myOkHttpUtils = new MyOkHttpUtils();
        params = new MyRequestParams();
    }

    /**
     * 展示银行卡列表的dialog
     */
    private void showSelectDialog() {

        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            BankListBean.DataEntity selectBank = bankCardAdapter.getItem(0);
            @Override
            public void onClick(DialogInterface dialog, int which) {
                LogUtils.e(TAG,"selectWhich:"+which);
                switch (which){
                    case -2:
                        break;
                    case -1:
                        DrawMoneyActivity.this.selectBank = this.selectBank;
                        initSelectBank(selectBank);
                        break;
                    default:
                        selectBank = bankCardAdapter.getItem(which);
                        bankCardAdapter.setCheckedPosition(which);
                        break;
                }
            }
        };
        AlertDialog.Builder builder = new AlertDialog.Builder(ctx)
                .setTitle("请选择银行")
                .setSingleChoiceItems(bankCardAdapter,0,listener)
                .setPositiveButton("确认",listener)
                .setNegativeButton("取消",listener);
        builder.create().show();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_select_bank:
                showSelectDialog();
                break;
            case R.id.btn_confirm_draw:
                if (selectBank==null){
                    showToast(ctx,"请选择银行卡!");
                    return;
                }
                String drawMoney = etInputPrice.getText().toString().trim();
                double money;
                try {
                    money = Double.parseDouble(drawMoney);
                } catch (NumberFormatException e) {
                    showToast(ctx,"请输入正确的金额!");
                    etInputPrice.setText("");
                    return;
                }
                if (money<0){
                    showToast(ctx,"请输入正确的金额!");
                    etInputPrice.setText("");
                    return;
                }
                if (money==0){
                    showToast(ctx,"金额不能为零!");
                    return;
                }
                withdrawMoney(selectBank.getB_ID()+"",money);
                break;
            case R.id.title_go_back:
                onBackPressed();
                break;
            case R.id.ll_add_bank:
                showSelectDialog();
                break;
            case R.id.tv_draw_money_all:
                etInputPrice.setText(drawableMoney+"");
        }
    }
    private static final int DRAWABLE_MONEY_REQUEST_OK = 6578;
    private static final int DRAW_MONEY_REQUEST_OK = 6445;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BANK_LIST_REQUEST_OK://获取银行卡列表成功,并且银行卡列表个数不为零
                    BankListBean bankList = (BankListBean) msg.obj;
                    bankCardAdapter.replace(bankList.getData());
                    // TODO: 2016/10/8 选择默认银行卡,如果没有默认则选择第一个

                    dismissDialog();
                    break;
                case BANK_LIST_REQUEST_FAIL://获取银行可列表失败
                    // TODO: 2016/10/8 改变页面为没有银行卡状态
                    dismissDialog();
                    break;
                case DRAW_MONEY_REQUEST_OK://提现成功
                    dismissDialog();
                    drawMoneyAmountRequest();

                case DRAWABLE_MONEY_REQUEST_OK://获取可提现金额成功
                    DrawMoneyAmountBean data = (DrawMoneyAmountBean) msg.obj;
                    if (data.getState()==1){
                        tvMoneyRemain.setText("余额："+data.getData());
                        try {
                            drawableMoney = Double.parseDouble(data.getData());
                        } catch (NumberFormatException e) {
                            tvMoneyRemain.setText("余额数据格式出错");
                        }

                    }else {
                        showToast(ctx,data.getMsg());
                    }
            }
        }
    };
}
